<script>
import { ref } from "vue";
import draggable from "vuedraggable";
import Compressor from "compressorjs";
import { UploadFilled } from "@element-plus/icons-vue";

export default {
  components: {
    draggable,
    UploadFilled,
  },
  props: {
    multiple: {
      type: Boolean,
      default: true,
    },
    limit: {
      type: Number,
      default: 9,
    },
    uploadFun: {
      type: Function,
    },
    compressOptions: {
      type: Object,
      default: () => {
        return {
          quality: 0.8,
          convertSize: 2000000,
        };
      },
    },
  },
  setup() {
    const images = ref([]);
    return {
      images,
    };
  },
  data() {
    return {
      drag: false,
    };
  },

  methods: {
    removeImage(index) {
      this.images.splice(index, 1);
    },
    handleDragChange(data) {
      const { element, oldIndex, newIndex } = data.moved;
      const newElement = this.images[oldIndex];
      this.images[oldIndex] = newElement;
      this.images[newIndex] = element;
    },
    handleUploadChange(_, fileList) {
      this.images = fileList;
    },
    async upload(option) {
      const { file } = option;
      const formData = new FormData();
      const compressedFile = await this.compress(file);
      formData.append("file", compressedFile, compressedFile.name);

      // 调用上传接口
      const url = await this.uploadFun(formData);
      return url;
    },
    // 压缩文件
    compress(fileOrBlob) {
      return new Promise((resolve, reject) => {
        new Compressor(fileOrBlob, {
          ...this.compressOptions,
          success: resolve,
          error: reject,
        });
      });
    },
  },
};
</script>

<template>
  <draggable
    class="uploader"
    v-model="images"
    item-key="uid"
    @change="handleDragChange"
    @start="drag = true"
    @end="drag = false"
  >
    <template #item="{ element, index }">
      <div
        style="display: inline-block; padding-right: 5px; padding-bottom: 5px"
      >
        <el-image
          style="display: block; width: 80px; height: 80px; border-radius: 5px"
          :src="element.url"
          fit="cover"
          :preview-src-list="images.map((image) => image.url || image.response)"
          :initial-index="index"
        />
        <el-button @click="removeImage(index)" style="width: 80px"
          >删除</el-button
        >
      </div>
    </template>

    <template #footer>
      <el-upload
        action=""
        :limit="limit"
        :multiple="multiple"
        :file-list="images"
        :http-request="upload"
        drag
        list-type="picture"
        :on-change="handleUploadChange"
        :auto-upload="true"
        :show-file-list="false"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">拖拽到这里上传</div>
      </el-upload>
    </template>
  </draggable>
</template>

<style>
.uploader {
  width: 100%;
}

.el-upload-dragger {
  padding: 10px;
}
</style>
